from vosk import Model, KaldiRecognizer
import os
import json
import threading
from service_functions import Cheek_Queue
import config
import obj_config
from language import language


class Speech_recognition:
    """Класс распознавания речи"""

    def vosk(self) -> None:
        """Функция распознавания речи.

        Функция работает в цикле и отправлет распознаную строку.

        В очередь queue в объект **stream_speech**.

        Функция становиться на паузу во время синтеза речи.
        """

        stop = 'False'
        flag = True
        check = Cheek_Queue(stop, flag)
        if not os.path.exists(config.model_mini_way):

            obj_config.communication_obj.messege(
                language["speech_recognition_work=>Speech_recognition=>vosk"]["error_mess"])
            exit(1)

        import pyaudio
        model = Model(config.model_mini_way)
        rec = KaldiRecognizer(model, 16000)
        p = pyaudio.PyAudio()
        stream = p.open(
            format=pyaudio.paInt16,
            channels=1,
            rate=16000,
            input=True,
            frames_per_buffer=8000)
        while True:
            check.set_Queue(config.stop_sr)
            state = check.cheek_Queue()
            if not state:
                stream.stop_stream()
            if state:
                stream.start_stream()
            if state:
                data = stream.read(4000)
                if len(data) == 0:
                    break
                if rec.AcceptWaveform(data) and config.resualt_sr == 0:
                    recognizer_json = rec.Result()
                    recognized_data = json.loads(recognizer_json)
                    recognized_str = recognized_data['text']
                    if len(recognized_str) > 0 and recognized_str != " ":
                        print(recognized_str)
                        config.stream_speech.put(recognized_str)
                        pass
                    else:
                        pass
                """
                else:
                    recognizer_json = rec.PartialResult()
                    recognized_data = json.loads(recognizer_json)
                    recognized_str = recognized_data['partial']
                    if len(recognized_str) > 0:
                        print(recognized_str)
                        #config.stream_speech_partial.put(recognized_str)
                        #pass
                        config.stream_speech.put(recognized_str)
                    else:
                        pass
                    """

    def thread(self) -> None:
        """Функция генерации потока распознавания речи
        """
        my_thread = threading.Thread(target=self.vosk)
        my_thread.start()

# ,daemon=True
